package com.lagou.edu.aop;

import com.lagou.edu.ioc.Autowired;
import com.lagou.edu.ioc.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 事务回调管理类
 */
public class TransactionalInvocationHandler implements InvocationHandler {


    private ITransactionManager transactionManager;

    private Object target;

    public TransactionalInvocationHandler(ITransactionManager transactionManager, Object target) {
        this.transactionManager = transactionManager;
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            // 开启事务
            transactionManager.beginTransaction();
            method.invoke(target, args);
            // 提交事务
            transactionManager.commit();
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback();
            e.printStackTrace();
            throw e;
        }
        return null;
    }
}
